package com.xh.fma.commodity.controller;

import com.xh.common.exception.FmaCodeExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import com.xh.common.utils.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 史建飞
 * @version 1.0
 */
@ResponseBody
@ControllerAdvice(basePackages = "com.xh.fma.commodity.controller")
@Slf4j
public class FmaExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题：{}, 异常类型：{}", e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item) ->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(FmaCodeExceptionEnum.INVALID_EXCEPTION.getCode(),FmaCodeExceptionEnum.INVALID_EXCEPTION.getMessage()).put("data",map);
    }


    @ExceptionHandler(value = Throwable.class)
    public R handleOtherException(Throwable e) {
        return R.error(FmaCodeExceptionEnum.UNKNOWN_EXCEPTION.getCode(),FmaCodeExceptionEnum.UNKNOWN_EXCEPTION.getMessage());
    }

}
